package com.teaching.teachingsupport.service.impl.studentserviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.teaching.teachingsupport.common.pojo.dataobject.*;
import com.teaching.teachingsupport.common.utils.SecurityUtils;
import com.teaching.teachingsupport.mapper.studentviewmapper.*;
import com.teaching.teachingsupport.mapper.TeacherMapper;
import com.teaching.teachingsupport.mapper.UserMapper;
import com.teaching.teachingsupport.service.service2.studentservice.HomeworkService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class HomeWorkServiceImpl implements HomeworkService {
    
    private final SecurityUtils securityUtil;
    private final StudentMapper studentMapper;
    private final HomeworkMapper homeworkMapper;
    private final StudentHomeworkMapper studentHomeworkMapper;
    private final CourseMapper courseMapper;
    private final TeacherMapper teacherMapper;
    private final UserMapper userMapper;
    private final CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<Homework> getHomework(Long userId) {
        // 获取学生信息
        Student student = studentMapper.selectOne(
            new LambdaQueryWrapper<Student>()
                .eq(Student::getUserId, userId)
        );

        if (student == null) {
            return List.of();
        }

        // 获取学生的作业信息
        List<StudentHomework> studentHomeworks = studentHomeworkMapper.selectList(
            new LambdaQueryWrapper<StudentHomework>()
                .eq(StudentHomework::getStudentId, student.getUserId())
        );

        // 获取作业详细信息并组装数据
        return studentHomeworks.stream().map(sh -> {
            Homework homework = homeworkMapper.selectById(sh.getHomeworkId());
            if (homework == null) {
                return null;
            }

            // 获取课程信息
            Course course = courseMapper.selectById(homework.getCourseId());
            if (course != null) {
                homework.setCourseName(course.getCourseName());
                homework.setCourseInfo(String.format("%s (%s) - %s学分", 
                    course.getCourseName(),
                    course.getCourseCode(),
                    course.getCredit()
                ));
            }

            // 获取作业发布者信息
            Teacher homeworkTeacher = teacherMapper.selectById(homework.getPublisherId());
            if (homeworkTeacher != null) {
                User teacherUser = userMapper.selectById(homeworkTeacher.getUserId());
                if (teacherUser != null) {
                    homework.setPublisherName(teacherUser.getUsername());
                }
            }

            // 设置学生作业状态和显示信息
            homework.setSubmitStatus(sh.getSubmitStatus());
            homework.setSubmitTime(sh.getSubmitTime());
            homework.setScore(sh.getScore());

            // 计算作业状态显示
            LocalDateTime now = LocalDateTime.now();
            if ("已批改".equals(sh.getSubmitStatus())) {
                // 已批改的作业显示分数
                String scoreDisplay = sh.getScore() + "/" + homework.getTotalScore() + "分";
                homework.setScoreDisplay(scoreDisplay);
                homework.setStatusDisplay(scoreDisplay);
            } else if (now.isAfter(homework.getDeadline())) {
                // 已截止的作业
                if ("未提交".equals(sh.getSubmitStatus())) {
                    homework.setStatusDisplay("已截止 0/" + homework.getTotalScore() + "分");
                } else {
                    homework.setStatusDisplay("已截止");
                }
            } else {
                // 未截止的作业，计算剩余时间
                long days = ChronoUnit.DAYS.between(now, homework.getDeadline());
                long hours = ChronoUnit.HOURS.between(now, homework.getDeadline()) % 24;
                long minutes = ChronoUnit.MINUTES.between(now, homework.getDeadline()) % 60;
                
                homework.setStatusDisplay(String.format("距离截止还有%d天%d小时%d分钟", days, hours, minutes));
            }

            return homework;
        })
        .filter(homework -> homework != null)
        .collect(Collectors.toList());
    }
}
